import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/core/models/point_exchange_account.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/screens/point/point_history_screen.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'components/point_type_in_sheet.dart';
import 'components/point_type_out_sheet.dart';

/// 积分兑换
class PointExchangeScreen extends StatefulWidget {
  static const routeName = '/PointExchangeScreen';

  @override
  _PointExchangeScreenState createState() => _PointExchangeScreenState();
}

class _PointExchangeScreenState extends State<PointExchangeScreen> {
  PointExchangeAccount _typeIn;
  PointExchangeAccount _typeOut;
  TextEditingController _outAmountController;
  TextEditingController _payPasswordController;
  TextEditingController _noteController;

  @override
  void initState() {
    super.initState();
    _outAmountController = TextEditingController();
    _payPasswordController = TextEditingController();
    _noteController = TextEditingController();
  }

  @override
  void dispose() {
    _outAmountController.dispose();
    _payPasswordController.dispose();
    _noteController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("积分兑换"),
      ),
      body: Container(
        padding: EdgeInsets.all(8.w),
        child: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                width: double.infinity,
                child: OutlineButton(
                  onPressed: _pointExchangeTypeIn,
                  child: Text(_typeIn?.name ?? "请选择兑入账户"),
                ),
              ),
              SizedBox(
                height: 8.w,
              ),
              Container(
                width: double.infinity,
                child: OutlineButton(
                  onPressed: _pointExchangeTypeOut,
                  child: Text(_typeOut?.name ?? "请选择兑出账户"),
                ),
              ),
              SizedBox(
                height: 8.w,
              ),
              TextField(
                controller: _outAmountController,
                decoration: InputDecoration(
                  hintText: "请输入兑出额度${_typeOut == null ? '' : '，必须是${_typeOut?.outAmountUnit}的整数'}",
                  filled: true,
                  fillColor: Colors.white,
                ),
                keyboardType: TextInputType.number,
              ),
              SizedBox(
                height: 8.w,
              ),
              TextField(
                controller: _payPasswordController,
                decoration: InputDecoration(
                  hintText: "请输入兑出账户的保护密码",
                  filled: true,
                  fillColor: Colors.white,
                ),
                obscureText: true,
              ),
              SizedBox(
                height: 8.w,
              ),
              TextField(
                controller: _noteController,
                decoration: InputDecoration(
                  hintText: "请输入备注信息",
                  filled: true,
                  fillColor: Colors.white,
                ),
              ),
              SizedBox(
                height: 8.w,
              ),
              Container(
                width: double.infinity,
                child: RaisedButton(
                  onPressed: _pointExchange,
                  child: Text("立即兑换"),
                ),
              ),
              SizedBox(
                height: 8.w,
              ),
              Container(
                width: double.infinity,
                child: RaisedButton(
                  onPressed: _pointExchangeHistory,
                  child: Text("兑换历史"),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 兑入账户
  void _pointExchangeTypeIn() async {
    final typeIn = await showModalBottomSheet<PointExchangeAccount>(
      context: context,
      builder: (context) {
        return PointTypeInSheet(
          displayBalance: true,
        );
      },
    );
    if (typeIn != null) {
      setState(() {
        _typeIn = typeIn;
      });
    }
  }

  /// 兑出账户
  void _pointExchangeTypeOut() async {
    if (_typeIn == null) {
      EasyLoading.showToast("请先选择兑入账户");
      return;
    }
    final typeOut = await showModalBottomSheet<PointExchangeAccount>(
      context: context,
      builder: (context) {
        return PointTypeOutSheet(
          inAccountType: _typeIn.accountType,
          displayBalance: true,
        );
      },
    );
    if (typeOut != null) {
      setState(() {
        _typeOut = typeOut;
      });
    }
  }

  /// 立即兑换
  void _pointExchange() async {
    final api = context.read<Api>();
    EasyLoading.show();
    try {
      await api.pointExchange(
        _typeIn?.accountType,
        _typeOut?.accountType,
        _outAmountController.text,
        _payPasswordController.text,
        _noteController.text,
      );
      EasyLoading.showToast("兑换成功");
    } on DioError catch (e) {
      EasyLoading.showToast("${e.message}");
    }
  }

  /// 兑换历史
  void _pointExchangeHistory() async {
    await Navigator.of(context).pushNamed(PointHistroyScreen.routeName);
    // 返回页面清除输入框
    _outAmountController.clear();
    _payPasswordController.clear();
    _noteController.clear();
  }
}
